# admin.py
from fastapi import APIRouter, Request
from fastapi.params import Depends

from ..ext import get_db
from ..models.crud import *
from sqlalchemy.orm import Session

router = APIRouter(
    prefix="/admin",  # 路由前缀
    tags=["管理员"],  # 用于在 Swagger UI 中显示的标签
    responses={404: {"description": "Not found"}},  # 404 错误响应
)


@router.get("/")
async def read_admin():
    return {"message": "Hello, Admin!"}


@router.post("/adduser")
async def add_user(request: Request, db: Session = Depends(get_db)):
    # 获取post请求的参数
    data = await request.json()
    username = data.get("name")
    age = data.get("age")
    # 性别
    gender = data.get("gender")
    data = create_user(name=username, gender=gender, age=age, db=db)
    return {"data": data}


# 查询有所数据
@router.get("/usersall")
async def get_all_users(db: Session = Depends(get_db)):
    data = get_users_all(db=db)
    return {"data": data}


# 查询单个用户通过用户名
@router.get("/user/{username}")
async def get_user_by_username(username: str, db: Session = Depends(get_db)):
    data = get_user_by_name(name=username, db=db)
    return {"data": data}


# 条件查询示例：查询年龄大于某个值的所有用户
@router.get("/users/age/{age}")
async def get_users_age(age, db: Session = Depends(get_db)):
    data = get_users_by_age(age=age, db=db)
    return {"data": data}


# 复合条件查询：查询年龄大于某个值且用户名包含特定字符串的用户
@router.get("/users/age/{age}/name/{name}")
async def get_users_age_name(age, name, db: Session = Depends(get_db)):
    data = get_users_by_age_and_name(age=age, name=name, db=db)
    return {"data": data}


# 分页查询
@router.get("/users/page/{page}")
async def get_users_page(page: int, db: Session = Depends(get_db)):
    data = get_users_by_page(page=page, db=db)
    return {"data": data}


# 更新用户信息
@router.put("/update/{username}")
async def update(username: str, request: Request, db: Session = Depends(get_db)):
    data = await request.form()
    print(data)
    # 获取需要更新的字段
    name = data.get("name")
    age = data.get("age")
    gender = data.get("gender")
    # 更新用户信息
    Up_User = update_user(name=name, age=age, gender=gender, db=db)
    return Up_User


# 删除用户
@router.delete("/delete/{username}")
async def delete_user(username: str, db: Session = Depends(get_db)):
    data = delete_user_by_name(name=username, db=db)
    return {"data": data}


# 批量删除用户
@router.delete("/deleteall/{age}")
async def delete_user_all(age: int, db: Session = Depends(get_db)):
    data = delete_users_by_age(age=age, db=db)
    return {"data": data}
